package com.seanliao.nav.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seanliao.nav.common.domain.dto.UserDTO;
import com.seanliao.nav.common.domain.vo.UserVO;
import com.seanliao.nav.common.exception.BusinessException;
import com.seanliao.nav.common.response.Result;
import com.seanliao.nav.common.response.ResultBuilder;
import com.seanliao.nav.entity.SysRole;
import com.seanliao.nav.entity.SysUser;
import com.seanliao.nav.service.ISysRoleService;
import com.seanliao.nav.service.ISysUserService;
import com.seanliao.nav.util.PasswordUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 用户管理
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final ISysUserService userService;
    private final ISysRoleService roleService;

    /**
     * 分页获取用户列表
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('user:page')")
    public Result<IPage<UserVO>> page(@RequestParam String page,
                                      @RequestParam String limit,
                                      @RequestParam(required = false) String roleName,
                                      @RequestParam(required = false) String username,
                                      @RequestParam(required = false) String nickname) {
        // 分页
        Page<UserVO> pp = new Page<>(Long.parseLong(page), Long.parseLong(limit));
        // 封装查询条件
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser.setNickname(nickname);
        SysRole sysRole = new SysRole();
        sysRole.setName(roleName);
        if (StrUtil.isNotBlank(roleName)) {
            pp = userService.pageUserByRole(pp, sysUser, sysRole);
        } else {
            pp = userService.pageUser(pp, sysUser);
        }
        return ResultBuilder.success(pp);
    }

    /**
     * 添加用户
     */
    @PostMapping("/add")
    @PreAuthorize("@pms.hasPermission('user:add')")
    public Result<?> add(@RequestBody UserDTO userDTO) {
        // 检查用户名重复
        Assert.isFalse(userService.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, userDTO.getUsername())
                .eq(SysUser::getIsDeleted, false)
        ) > 0, () -> new BusinessException("用户名已存在"));
        // 构建新用户
        SysUser sysUser = BeanUtil.copyProperties(userDTO, SysUser.class);
        // 密码加密 默认密码123456
        if (StrUtil.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(PasswordUtil.encode("123456"));
        } else {
            sysUser.setPassword(PasswordUtil.encode(sysUser.getPassword()));
        }
        // 入库
        if (userService.save(sysUser)) {
            return ResultBuilder.success();
        } else {
            return ResultBuilder.fail("数据写库异常");
        }
    }

    /**
     * 编辑用户
     */
    @PostMapping("/edit")
    @PreAuthorize("@pms.hasPermission('user:edit')")
    public Result<?> edit(@RequestBody UserDTO userDTO) {
        // 检查用户名重复
        Assert.isFalse(userService.count(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getUsername, userDTO.getUsername())
                .ne(SysUser::getId, userDTO.getId())
                .eq(SysUser::getIsDeleted, false)
        ) > 0, () -> new BusinessException("用户名已存在"));
        // 更新实体
        SysUser sysUser = BeanUtil.copyProperties(userDTO, SysUser.class);
        // 入库
        if (userService.updateById(sysUser)) {
            return ResultBuilder.success();
        } else {
            return ResultBuilder.fail("数据写库异常");
        }
    }

    /**
     * 绑定角色
     */
    @PostMapping("/bindRole")
    @PreAuthorize("@pms.hasPermission('user:bindRole')")
    public Result<?> bindRole(@RequestParam Long userId,
                              @RequestParam List<Long> roleIds) {
        roleService.editUserRole(userId, roleIds);
        return ResultBuilder.success();
    }

    /**
     * 禁用/解禁角色
     */
    @PostMapping("/ban")
    @PreAuthorize("@pms.hasPermission('user:ban')")
    public Result<?> banUser(@RequestParam Long userId,
                             @RequestParam Boolean isBan
    ) {
        // 更新实体
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setIsBan(isBan);
        // 入库
        if (userService.updateById(sysUser)) {
            return ResultBuilder.success();
        } else {
            return ResultBuilder.fail("数据写库失败");
        }
    }

}
